package com.paobuji.aidebao.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jaeger.library.StatusBarUtil;
import com.paobuji.aidebao.myapplication.activity.BaseActivity;
import com.paobuji.aidebao.myapplication.bean.BluResult;
import com.paobuji.aidebao.myapplication.bean.MyPlanCacheBean;
import com.paobuji.aidebao.myapplication.ble.entity.EntityDevice;
import com.paobuji.aidebao.myapplication.ble.service.BLEService;
import com.paobuji.aidebao.myapplication.ble.utils.BluetoothController;
import com.paobuji.aidebao.myapplication.ble.utils.ConstantUtils;
import com.paobuji.aidebao.myapplication.ble.utils.Util;
import com.paobuji.aidebao.myapplication.tool.ACache;
import com.paobuji.aidebao.myapplication.tool.BluDataUtil;
import com.paobuji.aidebao.myapplication.tool.DateUtil;
import com.paobuji.aidebao.myapplication.tool.SpUtil;
import com.paobuji.aidebao.myapplication.ui.MySportActivity;
import com.paobuji.aidebao.myapplication.ui.MySportHistoryActivity;
import com.paobuji.aidebao.myapplication.ui.MySportModelActivity;
import com.paobuji.aidebao.myapplication.ui.MyUserActivity;
import com.paobuji.aidebao.myapplication.ui.VedioActivity;
import com.paobuji.aidebao.myapplication.view.CustomTitlebar;
import com.paobuji.aidebao.myapplication.view.TargerSeekBar;

import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.paobuji.aidebao.myapplication.tool.Default.IS_CHINESE;

public class MainActivity extends BaseActivity {


    @BindView(R.id.mainTitle)
    CustomTitlebar mainTitle;
    @BindView(R.id.remberCon)
    ImageView remberCon;
    @BindView(R.id.remberText)
    TextView remberText;
    @BindView(R.id.modleCon)
    ImageView modleCon;
    @BindView(R.id.modelText)
    TextView modelText;
    @BindView(R.id.sportStartBut)
    Button sportStartBut;

    @BindView(R.id.tv_plan)
    TextView tv_plan;
    @BindView(R.id.tv_day)
    TextView tv_day;
    @BindView(R.id.tv_lc)
    TextView tv_lc;

    Intent intent;

    public double plan;         //计划目标距离
    public String startTime;    //开始时间
    public String stopTime;     //结束时间
    public double finish;       //已经完成距离

    MyPlanCacheBean myCacheBean;
    ACache aCache;
    Context context;
    @BindView(R.id.targerSeekBar)
    TargerSeekBar targerSeekBar;

    DateUtil dateUtil;
    BluetoothController controller;
    BluDataUtil bluDataUtil = new BluDataUtil();
    boolean isConnect = false;        //是否蓝牙已经连接
    boolean isCodeZero = false;        //s是否状态码正常
    BluResult bluResult;
    MsgReceiver receiver;
    Util u = new Util();
    String errorCode = "0";
    String stateCode = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去掉标题栏
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //initLanguage();
        setContentView(R.layout.activity_main);
        context = getApplicationContext();
        aCache = ACache.get(context);
        dateUtil = new DateUtil();
        //设置全透明
        StatusBarUtil.setTransparent(this);
        ButterKnife.bind(this);
        controller = BluetoothController.getInstance();
        myCacheBean = (MyPlanCacheBean) aCache.getAsObject("myCacheBean");
        if (myCacheBean == null) {
            myCacheBean = new MyPlanCacheBean();
            myCacheBean.setFinish(0);
            myCacheBean.setPlan(0);
            myCacheBean.setStartTime(DateUtil.getSysDate(0));
            myCacheBean.setStopTime(DateUtil.getSysDate(7));

            targerSeekBar.setOutMax(100);
            targerSeekBar.setInMax(7);
            targerSeekBar.setKmAndDay(0, 0);

            tv_plan.setText(getResources().getString(R.string.goalt) + ":" + 0);
            tv_day.setText(getResources().getString(R.string.day) + ":" + 0);
            tv_lc.setText(getResources().getString(R.string.mileage) + ":" + 0);

        } else {
//            targerSeekBar.setOutMax((int) myCacheBean.getPlan());
//            targerSeekBar.setInMax(dateUtil.differenceDate(myCacheBean.getStopTime(), myCacheBean.getStartTime()));
//            targerSeekBar.setKmAndDay((int) myCacheBean.getFinish(), dateUtil.differenceDate(dateUtil.getNowDate(), myCacheBean.getStartTime()));

            Log.e("11111", "initData: " + plan);
            Gson gson = new Gson();
            String s = gson.toJson(myCacheBean);
            Log.e("11111", "initData: " + s);

            tv_plan.setText(getResources().getString(R.string.goalt) + ":" + (int) myCacheBean.getPlan());
            tv_day.setText(getResources().getString(R.string.day) + ":" + dateUtil.differenceDate(dateUtil.getNowDate(), myCacheBean.getStartTime()));
            tv_lc.setText(getResources().getString(R.string.mileage) + ":" + (int) myCacheBean.getFinish());
        }

        //标题栏事件监测
        mainTitle.setAction(new CustomTitlebar.TitleBarOnClickListener() {
            @Override
            public void performAction(View view) {
                switch (view.getId()) {
                    case R.id.iv_left:
                        getUser();
                        //Toast.makeText(MainActivity.this, "左边图片按钮", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.tv_left:
                        getUser();
                        //Toast.makeText(MainActivity.this, "右边文字按钮", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.iv_right:
                        getBlue();
                        //Toast.makeText(MainActivity.this, "右边文字按钮", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.tv_right:
                        getBlue();
                        //Toast.makeText(MainActivity.this, "右边文字按钮", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
        inidBle();
    }

    //TODO
    //判断蓝牙是否已经连接
    //在跳转前开始跑步，在跳转
    public void inidBle() {


        //注册广播
        receiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConstantUtils.ACTION_RECEIVE_MESSAGE_FROM_DEVICE);
        intentFilter.addAction(ConstantUtils.ACTION_STOP_CONNECT);
        registerReceiver(receiver, intentFilter);


        if (!BluetoothController.getInstance().initBLE()) {                 //手机不支持蓝牙
            Toast.makeText(this, "您的手机不支持蓝牙",
                    Toast.LENGTH_SHORT).show();
            return;//手机不支持蓝牙就啥也不用干了，关电脑睡觉去吧
        }
        if (!BluetoothController.getInstance().isBleOpen()) {
            Toast.makeText(this, "MainActivity",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if(!isServiceRunning(context,"com.paobuji.aidebao.myapplication.ble.service.BLEService")){
            //开始服务
            Intent   intentService = new Intent(this, BLEService.class);
            startService(intentService);
            //初始化蓝牙
            BluetoothController.getInstance().initBLE();
            Log.i("蓝牙","蓝牙启动");
        }



        EntityDevice bleEntityDevice = (EntityDevice) aCache.getAsObject("BleEntityDevice");
        Gson gson = new Gson();
        String s = gson.toJson(bleEntityDevice);
        Log.e("11111 bleEntityDevice", "initData: " + s);
        if (null != bleEntityDevice) {
            if (BluetoothController.reBtGatt() == null) {
                //连接设备
                Log.e("11111 bleEntityDevice", "initData:1 " );
                BluetoothController.getInstance().connect(bleEntityDevice);
            } else {
                BluetoothController.clearBtGatt();
                Log.e("11111 bleEntityDevice", "initData:2 " );

                BluetoothController.getInstance().connect(bleEntityDevice);
                Log.e("11111 bleEntityDevice", "initData:3" );


            }

        }


}

/**
 * 接收广播，接收蓝牙模块发过来的值
 */
public class MsgReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equalsIgnoreCase(ConstantUtils.ACTION_STOP_CONNECT)) {
            Log.i("蓝牙", "连接已断开");
            isConnect = false;
            mainTitle.setRightIcon(R.mipmap.bled);
        } else if (intent.getAction().equalsIgnoreCase(ConstantUtils.ACTION_RECEIVE_MESSAGE_FROM_DEVICE)) {
            //receivedMessage.append(u.toStringHex(intent.getStringExtra("message")).trim());
            // Log.i("蓝牙数据", u.toStringHex(intent.getStringExtra("message")).trim());
            isConnect = true;
            mainTitle.setRightIcon(R.mipmap.bleb);

            try {
                bluResult = bluDataUtil.SplitStr(u.toStringHex(intent.getStringExtra("message")).trim(), context);
                if (bluResult != null) {
                    if (bluResult.code.equals("0")) {
                        isCodeZero = true;
                        stateCode = bluResult.state;
                        if (Float.parseFloat(bluResult.speed) > 0.3) {
                            sportStartBut.setText(getString(R.string.goRun));
                        }
                    } else if (bluResult.code.equals("1")) {
                        isCodeZero = false;
                        errorCode = "E01";
                    } else if (bluResult.code.equals("2")) {
                        isCodeZero = false;
                        errorCode = "E02";
                    } else if (bluResult.code.equals("3")) {
                        isCodeZero = false;
                        errorCode = "E03";
                    } else if (bluResult.code.equals("4")) {
                        isCodeZero = false;
                        errorCode = "E04";
                    } else if (bluResult.code.equals("5")) {
                        isCodeZero = false;
                        errorCode = "E05";
                    } else if (bluResult.code.equals("6")) {
                        isCodeZero = false;
                        errorCode = "E06";
                    } else if (bluResult.code.equals("7")) {
                        isCodeZero = false;
                        errorCode = "E07";
                    }
                }
                //
                // Log.i("jianbaopp",errorCode);
            } catch (Exception e) {

            }
        }
    }

}

    //初始化数据显示
    @Override
    public void initView() {

    }

    @Override
    protected void initData() {
        Log.e("11111", "initData: ");
        myCacheBean = (MyPlanCacheBean) aCache.getAsObject("myCacheBean");

        if (myCacheBean != null) {


            plan = myCacheBean.getPlan();
            startTime = myCacheBean.getStartTime();
            stopTime = myCacheBean.getStopTime();
            finish = myCacheBean.getFinish();
            Log.e("11111", "initData: " + plan);
            Gson gson = new Gson();
            String s = gson.toJson(myCacheBean);
            Log.e("11111", "initData: " + s);


            tv_plan.setText(getResources().getString(R.string.goalt) + ":" + (int) myCacheBean.getPlan());
            tv_day.setText(getResources().getString(R.string.day) + ":" + dateUtil.differenceDate(dateUtil.getNowDate(), myCacheBean.getStartTime()));
            tv_lc.setText(getResources().getString(R.string.mileage) + ":" + (int) myCacheBean.getFinish());
        }
        Log.e("11111", "initData: ");

    }

    /**
     * 跳转，前往历史记录界面
     */
    public void goHistory() {
        intent = new Intent(MainActivity.this, MySportHistoryActivity.class);
        startActivity(intent);
    }

    /**
     * 跳转，前往模式设置界面
     */
    public void getModel() {
        if (isConnect) {
            //Toast.makeText(MainActivity.this,"ERROR: " + errorCode,Toast.LENGTH_LONG).show();
            if (isCodeZero) {
                if ("60".equals(stateCode)) {
                    Toast.makeText(MainActivity.this, getResources().getString(R.string.noSalf), Toast.LENGTH_LONG).show();
                } else {
                    intent = new Intent(MainActivity.this, MySportModelActivity.class);
                    startActivity(intent);
                }
            } else {
                Toast.makeText(MainActivity.this, "ERROR: " + errorCode, Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(MainActivity.this, R.string.connectBluetooth, Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 跳转，前往个人中心界面
     */
    public void getUser() {
        intent = new Intent(MainActivity.this, MyUserActivity.class);
        startActivityForResult(intent, 0);
    }

    /**
     * 跳转，前往蓝牙界面
     */
    public void getBlue() {
        intent = new Intent(MainActivity.this, MySportActivity.class);
        startActivity(intent);
    }

    /**
     * 跳转，前往跑步界面
     */
    public void getSport() {
        if (isConnect) {
            if (isCodeZero) {
                if ("60".equals(stateCode)) {
                    Toast.makeText(MainActivity.this, getResources().getString(R.string.noSalf), Toast.LENGTH_LONG).show();
                } else {

                    aCache.put("modelboolean", "false");
                    controller.write(bluDataUtil.startStop("1"));
                    intent = new Intent(MainActivity.this, VedioActivity.class);
                    startActivity(intent);
                }
            } else {
                Toast.makeText(MainActivity.this, "ERROR: " + errorCode, Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(MainActivity.this, R.string.connectBluetooth, Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick({R.id.remberCon, R.id.remberText, R.id.modleCon, R.id.modelText, R.id.sportStartBut})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.remberCon:
                goHistory();
                break;
            case R.id.remberText:
                goHistory();
                break;
            case R.id.modleCon:
                getModel();
                break;
            case R.id.modelText:
                getModel();
                break;
            case R.id.sportStartBut:
                getSport();
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        //设置为竖屏
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    /**
     * 从SP中取值，如果选择过语言就直接使用，没有的话就使用系统默认的语言
     */
    private void initLanguage() {
        /*SpUtil.setInt(SpUtil.LANGUAGE, SpUtil.ENG);
        setLanguageView("_EN");*/
        int anInt = SpUtil.getInt(SpUtil.LANGUAGE);
        if (anInt == -1) {
            String language = Locale.getDefault().getLanguage();
            // en  zh
            if (TextUtils.isEmpty(language)) {
                return;
            }

            if ("en".equals(language)) {
                IS_CHINESE = false;

                SpUtil.setInt(SpUtil.LANGUAGE, SpUtil.ENG);
                setLanguageView("_EN");
            } else if ("zh".equals(language)) {
                IS_CHINESE = true;

                SpUtil.setInt(SpUtil.LANGUAGE, SpUtil.ZH);
                setLanguageView("_ZH");
            }
        } else {
            if (anInt == SpUtil.ENG) {
                IS_CHINESE = false;

                SpUtil.setInt(SpUtil.LANGUAGE, SpUtil.ENG);
                setLanguageView("_EN");
            } else if (anInt == SpUtil.ZH) {
                IS_CHINESE = true;

                SpUtil.setInt(SpUtil.LANGUAGE, SpUtil.ZH);
                setLanguageView("_ZH");
            }
        }
    }

    public void setLanguageView(String language) {
        //获取当前资源对象
        Resources resources = getResources();
        //获取设置对象
        Configuration configuration = resources.getConfiguration();
        //获取屏幕参数
        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        //设置本地语言
        switch (language) {
            case "_ZH":
                configuration.locale = Locale.CHINA;//中文
                break;
            case "_EN":
                configuration.locale = Locale.ENGLISH;
                break;
            case "_JA":
                configuration.locale = Locale.JAPAN;
                break;
            case "_FR":
                configuration.locale = Locale.FRANCE;
                break;
            case "_ES":
                configuration.locale = new Locale("ES");
                break;
            case "_KO":
                //韩国
                configuration.locale = new Locale("KO");
                break;
            case "_IT":
                //意大利
                configuration.locale = new Locale("IT");
                break;
            case "_PT":
                //葡萄牙
                configuration.locale = new Locale("PT");
                break;
            case "_DE":
                //德国
                configuration.locale = Locale.GERMAN;
                break;
            case "_AR":
                //阿拉伯
                configuration.locale = new Locale("AR");
                break;
            case "_RU":
                //俄语
                configuration.locale = new Locale("RU");
                break;
        }
        resources.updateConfiguration(configuration, displayMetrics);

        //如果你的MainActivity是SingleTask需要这样重新启动Activity
        /*Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);*/
    }


}
